package com.apisix.service.service;

import com.apisix.service.entity.Consumer;
import com.apisix.service.repository.ConsumerRepository;
import com.apisix.service.util.KeyGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class ConsumerService {

    private final ConsumerRepository consumerRepository;
    private final ApisixService apisixService;

    @Autowired
    public ConsumerService(ConsumerRepository consumerRepository, ApisixService apisixService) {
        this.consumerRepository = consumerRepository;
        this.apisixService = apisixService;
    }

    public List<Consumer> getAllConsumers() {
        return consumerRepository.findAll();
    }

    public Optional<Consumer> getConsumerById(Long id) {
        return consumerRepository.findById(id);
    }

    public Optional<Consumer> getConsumerByAppId(String appId) {
        return consumerRepository.findByAppId(appId);
    }

    @Transactional
    public Consumer createConsumer(Consumer consumer) throws NoSuchAlgorithmException, IOException {
        // 生成RSA密钥对
        Map<String, String> keyPair = KeyGeneratorUtil.generateRSAKeyPair();
        consumer.setRsaPublicKey(keyPair.get("publicKey"));
        consumer.setRsaPrivateKey(keyPair.get("privateKey"));
        
        // 保存到数据库
        Consumer savedConsumer = consumerRepository.save(consumer);
        
        // 在APISIX中创建
        apisixService.createConsumer(savedConsumer);
        
        return savedConsumer;
    }

    @Transactional
    public Optional<Consumer> updateConsumer(Long id, Consumer consumerDetails) {
        return consumerRepository.findById(id)
                .map(existingConsumer -> {
                    existingConsumer.setAppSecret(consumerDetails.getAppSecret());
                    existingConsumer.setDescription(consumerDetails.getDescription());
                    
                    // 更新应用名称
                    if (consumerDetails.getAppName() != null && !consumerDetails.getAppName().trim().isEmpty()) {
                        existingConsumer.setAppName(consumerDetails.getAppName());
                    }
                    
                    Consumer updatedConsumer = consumerRepository.save(existingConsumer);
                    
                    // 在APISIX中更新
                    apisixService.createConsumer(updatedConsumer);
                    
                    return updatedConsumer;
                });
    }

    @Transactional
    public boolean deleteConsumer(Long id) {
        return consumerRepository.findById(id)
                .map(consumer -> {
                    // 首先从APISIX中删除
                    apisixService.deleteConsumer(consumer.getAppId());
                    
                    // 然后从数据库中删除
                    consumerRepository.delete(consumer);
                    return true;
                })
                .orElse(false);
    }

    public boolean existsByAppId(String appId) {
        return consumerRepository.existsByAppId(appId);
    }
} 